package cn.ffcs.uec.outStaff.component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Div;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.uec.common.util.PermissionUtil;
import cn.ffcs.uec.outStaff.component.bean.UecOutStaffNationdutyListboxBean;
import cn.ffcs.uec.outStaff.constant.UecOutStaffConstants;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.staff.manager.UecNationdutyManager;
import cn.ffcs.uec.staff.model.UecNationduty;
import cn.ffcs.uom.common.constants.BaseUnitConstants;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.IPortletInfoProvider;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.PageInfo;
import cn.ffcs.uom.common.zul.PubUtil;
import lombok.Getter;
import lombok.Setter;

/**
 * @Title:职业资格管理 CRUD插件
 * @Description:
 * @Company: FFCS
 * @since JDK1.6
 */
@Controller
@Scope("prototype")
public class UecOutStaffNationdutyListboxExt extends Div implements IdSpace {

	private static final long serialVersionUID = -5811398149406451671L;
	/**
	 * 人员基本信息功能 查询出的实体对象
	 */
	private UecOutStaffInfo uecStaffInfo;
	/**
	 * 对应页面上的bean
	 */
	@Getter
	private UecOutStaffNationdutyListboxBean bean = new UecOutStaffNationdutyListboxBean();
	/**
	 * 职业资格管理实体
	 */
	private UecNationduty uecNationduty;
	/**
	 * 翻页查询条件实体
	 */
	private UecNationduty nationdutyPaging;

	private UecNationduty approvalNationdutyPaging;
	/**
	 * 职业资格管理查询实体
	 */

	private UecNationdutyManager uecNationdutyManager = (UecNationdutyManager) ApplicationContextUtil
			.getBean("uecNationdutyManager");

	private List<UecNationduty> nationdutyList = new ArrayList<UecNationduty>();

	/**
	 * 是否由外包入职申请页引用
	 */
	private boolean isOutStaffEntryExt = false;

	@Getter
	@Setter
	private IPortletInfoProvider portletInfoProvider;

	public UecOutStaffNationdutyListboxExt() {
		Executions.createComponents(
				UecOutStaffConstants.UEC_OUT_STAFF_NATION_DUTY_EXT_LISTBOX_ZUL,
				this, null);
		Components.wireVariables(this, bean);
		Components.addForwards(this, this, '$');

		this.addForward(
				UecOutStaffConstants.ON_UEC_OUT_STAFF_NATION_DUTY_QUERY,
				this,
				UecOutStaffConstants.ON_UEC_OUT_STAFF_NATION_DUTY_QUERY_RESPONSE);

		this.addForward(
				UecOutStaffConstants.ON_UEC_OUT_STAFF_NATION_DUTY_QUERY_OF_OUTSTAFF_ENTRY,
				this,
				UecOutStaffConstants.ON_UEC_OUT_STAFF_NATION_DUTY_QUERY_OF_OUTSTAFF_ENTRY_RESPONSE);

		this.addForward(
				UecOutStaffConstants.ON_UEC_OUT_STAFF_NATION_DUTY_QUERY_OF_OUTSTAFF_ENTRY_VIEW,
				this,
				UecOutStaffConstants.ON_UEC_OUT_STAFF_NATION_DUTY_QUERY_OF_OUTSTAFF_ENTRY_VIEW_RESPONSE);

		this.addForward(
				UecOutStaffConstants.ON_CLEAN_UEC_OUT_STAFF_NATION_DUTY,
				this,
				UecOutStaffConstants.ON_CLEAN_UEC_OUT_STAFF_NATION_DUTY_RESPONSE);

	}

	/**
	 * 初始化
	 */
	public void onCreate() {
		this.setButtonValid(false, false, false, false);
	}

	/**
	 * 选择查询记录
	 * 
	 * @throws Exception
	 */
	public void onSelectUecNationdutyList() throws Exception {
		if (this.bean.getUecNationdutyListbox().getSelectedCount() > 0) {
			uecNationduty = (UecNationduty) bean.getUecNationdutyListbox()
					.getSelectedItem().getValue();
		}
	}

	/**
	 * 人员基本信息功能，抛出事件， 事件监听
	 * 
	 * @param event
	 */
	public void onUecOutStaffNationdutyQueryResponse(ForwardEvent event) {
		uecStaffInfo = (UecOutStaffInfo) event.getOrigin().getData();
		if (null != uecStaffInfo) {
	        //设置操作按钮，非盟市主管不可操作按钮
	        if(PermissionUtil.isNoMainOutStaff()) {
	            this.setButtonValid(false, true, true, true);
	        }else {
	            this.setButtonValid(true, true, true, false);
	        }
			uecNationduty = new UecNationduty();
			uecNationduty.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
			uecNationduty.setStaffId(uecStaffInfo.getOutStaffId());
			nationdutyPaging = uecNationduty;
			this.onQueryUecNationduty();
		}
	}

	/**
	 * 人员基本信息功能，抛出事件， 事件监听,来自人员入职
	 * 
	 * @param event
	 */
	@SuppressWarnings("unchecked")
	public void onUecOutStaffNationdutyQueryOfOutStaffEntryResponse(
			ForwardEvent event) {
		Map<String, Object> map = (Map<String, Object>) event.getOrigin()
				.getData();
		if (null != map) {
			isOutStaffEntryExt = (Boolean) map.get("isOutStaffEntryExt");
			uecStaffInfo = (UecOutStaffInfo) map.get("uecOutStaffInfo");
			if (null != uecStaffInfo) {
				uecNationduty = new UecNationduty();
				uecNationduty
						.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
				uecNationduty.setStaffId(uecStaffInfo.getOutStaffId());
				this.setButtonValid(true, true, true, false);

				ListModel list = new BindingListModelList(nationdutyList, true);
				this.bean.getUecNationdutyListbox().setModel(list);
				this.bean.getUecNationdutyListboxPaging().setTotalSize(1);

				uecNationduty = null;
			}
		}

	}

	/**
	 * 职业资格管理审批信息id，抛出事件， 事件监听
	 * 
	 * @param event
	 */
	public void onUecOutStaffNationdutyQueryOfOutStaffEntryViewResponse(
			ForwardEvent event) {
		nationdutyList.clear();
		approvalNationdutyPaging = new UecNationduty();
		String nationdutyIds = (String) event.getOrigin().getData();
		if (!StrUtil.isNullOrEmpty(nationdutyIds)) {
			String[] nationdutyIdArray = nationdutyIds.split("-");
			if (!StrUtil.isNullOrEmpty(nationdutyIdArray)
					&& nationdutyIdArray.length > 0) {
				for (String nationdutyId : nationdutyIdArray) {
					UecNationduty uecNationduty = UecNationduty.newInstance();
					uecNationduty.setNationdutyId(Long.valueOf(nationdutyId));
					uecNationduty = uecNationdutyManager
							.queryUecNationdutyByNationdutyId(uecNationduty);
					nationdutyList.add(uecNationduty);
				}

				onQueryUecNationduty();
			}
		}

	}

	public void onCleanUecOutStaffNationdutyResponse(ForwardEvent event) {
		clearVariable();
		uecStaffInfo = null;
		ListboxUtils.clearListbox(this.bean.getUecNationdutyListbox());
		this.bean.getUecNationdutyListboxPaging().setTotalSize(1);
	}

	/**
	 * 设置按钮
	 * 
	 * @param canAdd
	 * @param candel
	 */
	private void setButtonValid(boolean canView, boolean canAdd,
			boolean canEdit, boolean candel) {
		this.bean.getViewButton().setDisabled(!canView);
		this.bean.getAddButton().setDisabled(!canAdd);
		this.bean.getEditButton().setDisabled(!canEdit);
		this.bean.getDelButton().setDisabled(!candel);
	}

	/**
	 * 查询按钮
	 */
	public void onQueryUecNationduty() {
		this.bean.getUecNationdutyListboxPaging().setActivePage(0);
		this.onQueryUecNationdutyList();
	}

	/**
	 * 重置按钮
	 */
	public void onResetUecNationduty() {
		ListboxUtils.clearListbox(this.bean.getUecNationdutyListbox());
		this.bean.getUecNationdutyListboxPaging().setTotalSize(1);
	}

	/**
	 * 查看按钮
	 * 
	 * @throws Exception
	 * @throws InterruptedException
	 */
	public void onViewUecNationduty() throws Exception, InterruptedException {
		if (uecNationduty != null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "view");
			map.put("uecNationduty", uecNationduty);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_STAFF_NATION_DUTY_EDIT_ZUL,
					this, map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						//
					}
				}
			});
		} else {
			ZkUtil.showError("请选中要查看的记录", "提示信息");
		}
	}

	/**
	 * 新增按钮
	 * 
	 * @throws Exception
	 * @throws
	 */
	public void onAddUecNationduty() throws Exception {
		if (null != uecStaffInfo) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "add");
			map.put("uecOutStaffInfo", uecStaffInfo);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_STAFF_NATION_DUTY_EDIT_ZUL,
					this, map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						// 新增或修改完成后，列表从数据库更新
						uecNationduty = (UecNationduty) event.getData();
						nationdutyList.add(uecNationduty);
						if (!isOutStaffEntryExt) {
							onQueryUecNationdutyList();
						} else {
							ListModel list = new BindingListModelList(
									nationdutyList, true);
							bean.getUecNationdutyListbox().setModel(list);
							bean.getUecNationdutyListboxPaging()
									.setTotalSize(1);

							postNationdutyList();
						}

					}
				}
			});
		}
	}

	/**
	 * 抛出事件，把添加的列表发送给OutStaffEntryExt
	 */
	private void postNationdutyList() {
		Events.postEvent("onPostNationdutyListOfOutStaffEntry", this,
				nationdutyList);
	}

	/**
	 * 编辑按钮
	 * 
	 * @throws Exception
	 * @throws InterruptedException
	 */
	public void onEditUecNationduty() throws Exception, InterruptedException {
		if (null != uecNationduty) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "edit");
			map.put("uecNationduty", uecNationduty);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_STAFF_NATION_DUTY_EDIT_ZUL,
					this, map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						if (isOutStaffEntryExt) {
							nationdutyList.remove(uecNationduty);
						}
						uecNationduty = (UecNationduty) event.getData();
						// 新增或修改完成后，列表从数据库更新
						if (!isOutStaffEntryExt) {
							onQueryUecNationdutyList();
						} else {
							nationdutyList.add(uecNationduty);
							ListModel list = new BindingListModelList(
									nationdutyList, true);
							bean.getUecNationdutyListbox().setModel(list);
							bean.getUecNationdutyListboxPaging()
									.setTotalSize(1);

							postNationdutyList();
						}

					}
				}
			});
		} else {
			ZkUtil.showError("请选中要编辑的记录", "提示信息");
			return;
		}
	}

	/**
	 * 审批状态中修改
	 * 
	 * @throws InterruptedException
	 * @throws SuspendNotAllowedException
	 */
	public void onApprovalEditUecNationduty()
			throws SuspendNotAllowedException, InterruptedException {
		if (null != uecNationduty && uecNationduty.getId() != null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "approvalEdit");
			map.put("uecNationduty", uecNationduty);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_STAFF_NATION_DUTY_EDIT_ZUL,
					this, map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						uecNationduty = (UecNationduty) event.getData();
						// 新增或修改完成后，列表从数据库更新
						PageInfo pageInfo = uecNationdutyManager
								.queryPageInfoByUecNationdutyOnApproval(
										uecNationduty,
										bean.getUecNationdutyListboxPaging()
												.getActivePage() + 1,
										bean.getUecNationdutyListboxPaging()
												.getPageSize());
						ListModel list = new BindingListModelList(pageInfo
								.getDataList(), true);
						bean.getUecNationdutyListbox().setModel(list);
						bean.getUecNationdutyListboxPaging().setTotalSize(1);
					}
				}
			});
		} else {
			ZkUtil.showError("请选中要修改的记录", "提示信息");
			return;
		}

	}

	/**
	 * 删除按钮
	 */
	public void onDelUecNationduty() {
		if (this.uecNationduty != null && uecNationduty.getId() != null) {
			ZkUtil.showQuestion("确定要删除吗?", "提示信息", new EventListener() {
				public void onEvent(Event event) throws Exception {
					Integer result = (Integer) event.getData();
					if (result == Messagebox.OK) {
						uecNationduty.removeOnly();
						PubUtil.reDisplayListbox(
								bean.getUecNationdutyListbox(), uecNationduty,
								"del");
						uecNationduty = null;
					}
				}
			});
		} else {
			ZkUtil.showError("请选中要删除的记录", "提示信息");
			return;
		}
	}

	/**
	 * 翻页
	 */
	public void onUecOutNationdutyListboxPaging() {
		this.onQueryUecNationdutyList();
	}

	/**
	 * 清除变量
	 */
	public void clearVariable() {
		uecNationduty = null;
		nationdutyPaging = null;
		nationdutyList.clear();
	}

	/**
	 * 查询
	 */
	public void onQueryUecNationdutyList() {
		if (null != nationdutyPaging) {
			PageInfo pageInfo = uecNationdutyManager
					.queryPageInfoByUecNationduty(nationdutyPaging,
							this.bean.getUecNationdutyListboxPaging()
									.getActivePage() + 1, this.bean
									.getUecNationdutyListboxPaging()
									.getPageSize());
			ListModel list = new BindingListModelList(pageInfo.getDataList(),
					true);
			this.bean.getUecNationdutyListbox().setModel(list);
			this.bean.getUecNationdutyListboxPaging().setTotalSize(
					pageInfo.getTotalCount());

		}
		if (null != approvalNationdutyPaging) {
//			List<UecNationduty> pageNationduties = getCurrentPageList(nationdutyList,
//					bean.getUecNationdutyListboxPaging().getActivePage() + 1,
//					bean.getUecNationdutyListboxPaging().getPageSize());
			ListModel list = new BindingListModelList(nationdutyList, true);
			this.bean.getUecNationdutyListbox().setModel(list);
			this.bean.getUecNationdutyListboxPaging().setTotalSize(1);
		}
		// 入职 页添加记录后，不选择记录时 点击 查看 编辑 按钮 不弹出弹窗
		uecNationduty = null;

	}

	/**
	 * 获取当前页list
	 * 
	 * @param list
	 * @param activePage
	 * @param pageSize
	 * @return
	 */
	public List<UecNationduty> getCurrentPageList(List<UecNationduty> list,
			int activePage, int pageSize) {
		int fromIndex = activePage * pageSize;
		int toIndex = fromIndex + pageSize;
		if (fromIndex >= list.size()) {
			return null;
		}
		if (toIndex >= list.size()) {
			return list.subList(fromIndex, list.size());
		}
		return list.subList(fromIndex, toIndex);

	}

}
